import { observable, action } from 'mobx';
import { ListViewPage, RouteLayout, Reply } from 'weaver-mobile-page';
import * as Apis from "../../api/customerApis";
import { Toast, Modal, Tools, Bubble } from 'weaver-mobile';
import { toJS } from 'mobx';
import * as adapter from '../../constants/adapter';

const alert = Modal.alert;
const getLabel = Tools.getLabel;

export default class ContactListStore {
  comObj = {};
  params = {};
  replyRef = {};
  @observable showCheck = false;
  @observable showOutInput = false;
  @observable list = {};
  @observable initResponsed = false;// 是否已经得到初始化数据的响应
  @observable initSuccessed = false;// 初始化数据是否获取成功
  @observable initFailedMsg = "";   // 初始化处理失败的原因
  @observable relatedCustomerLayout = {};
  @observable relatedChanceLayout = {};
  @observable relatedContacterLayout = {};
  @observable replyStore = new Reply.Store({ getAttachList: this.getAttachList });
  @observable remarkStore = new Reply.Store();
  @observable photoFiles = [];
  @observable photoIndex = 0;
  @observable photoVisible = false;
  @observable remark = {};
  @observable callback;
  @observable contactWay = [];
  @action
  doNew = (comObj, params) => {
    this.comObj = comObj;
    this.params = params;
  }

  @action
  doInit = () => {
    let params = this.params;
    this.doInitCallBack(params);
  }

  @action
  doInitCallBack = (params) => {
    this.initResponsed = true;
    this.initSuccessed = true;
    const currentPath = this.comObj.props.location.pathname;
    this.list = new ListViewPage.Store({ route: currentPath, id: "contactList" });
    this.relatedCustomerLayout = new RouteLayout.Store({ route: currentPath, id: 'relatedCustomerLayout' });
    this.relatedChanceLayout = new RouteLayout.Store({ route: currentPath, id: 'relatedChanceLayout' });
    this.relatedContacterLayout = new RouteLayout.Store({ route: currentPath, id: 'relatedContacterLayout' });
    this.doSearch();
  }

  @action
  doSearch = () => {
    let params = this.params;
    Apis.getContactListResult(params).then(data => {
      const dataKey = data.datas;
      this.list.clearData();
      this.list.getData({ dataKey });
      this.contactWay = data.contactWay || [];
      // console.log(toJS(this.contactWay));
      this.replyStore.getAttachLists();
    });
  }

  @action
  doClear = () => {
    this.initResponsed = false;
    this.initSuccessed = false;
    this.initFailedMsg = "";
    this.showOutInput = false;
    this.photoVisible = false;
    this.photoIndex = 0;
    this.photoFiles = [];
  }

  @action
  saveReply(datas) {
    // console.log("datas",datas);
    let workflows = "";
    let docs = "";
    let projects = "";
    // let taskes = "";
    let chances = "";
    let contacters = "";
    let contactWay = "";
    let imgs = "";
    let attachs = "";
    if (datas.attach.workFlow) {
      for (let obj of datas.attach.workFlow) {
        workflows += obj.id + ",";
      }
      workflows = workflows.substring(0, workflows.length - 1);
    }
    if (datas.attach.document) {
      for (let obj of datas.attach.document) {
        docs += obj.id + ",";
      }
      docs = docs.substring(0, docs.length - 1);
    }
    if (datas.attach.project) {
      for (let obj of datas.attach.project) {
        projects += obj.id + ",";
      }
      projects = projects.substring(0, projects.length - 1);
    }
    // if(datas.attach.task){
    //   for(let obj of datas.attach.task){
    //     taskes += obj.id + ",";
    //   }
    //   taskes = taskes.substring(0,taskes.length - 1);
    // }
    if (datas.attach.chance) {
      for (let obj of datas.attach.chance) {
        chances += obj.id + ",";
      }
      chances = chances.substring(0, chances.length - 1);
    }
    if (datas.attach.contacter) {
      for (let obj of datas.attach.contacter) {
        contacters += obj.id + ",";
      }
      contacters = contacters.substring(0, contacters.length - 1);
    }
    if (datas.imgList) {
      for (let obj of datas.imgList) {
        imgs += obj.fileid + ",";
      }
      imgs = imgs.substring(0, imgs.length - 1);
    }
    if (datas.attach.file) {
      for (let obj of datas.attach.file) {
        attachs += obj.id + ",";
      }
      attachs = attachs.substring(0, attachs.length - 1);
    }
    if (datas.attach.contactWay) {
      contactWay = datas.attach.contactWay[0];
    }
    if (!datas.attach.contactWay || datas.attach.contactWay.length == 0 || contactWay == "") {
      Bubble.warning(getLabel('514789', "请选择联系方式"), 3, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2);
      return;
    }
    // console.log("workflows",workflows);
    // console.log("docs",docs);
    // console.log("projects",projects);
    // console.log("taskes",taskes);
    // console.log("chances",chances);
    // console.log("contacters",contacters);
    // console.log("imgs",imgs);
    // console.log("attachs",attachs);
    // this.replyStore.doClear();
    // console.log("replyStore",toJS(this.replyStore));
    let crmid;
    if (this.params.rightType) {
      if (datas.attach.customer) {
        crmid = datas.attach.customer[0].id;
      } else {
        Bubble.warning(getLabel('502475', "相关客户不能为空"), 3, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2);
        return;
      }
    } else {
      crmid = this.params.customerId;
    }
    const params = { customerId: crmid, chances: chances, contacters: contacters, description: datas.text.replace(/&lt;/g, "<").replace(/&gt;/, ">") , workflows: workflows, docs: docs, projects: projects, imgs: imgs, attachs: attachs, contactWay: contactWay }
    Toast.loading(getLabel('388626', '正在保存，请稍后...'), 0);
    this.replyRef.setVisible(false);
    Apis.saveContactForm(params).then(data => {
      Toast.hide();
      if (data.status == "0") {
        Bubble.error(getLabel(22620, '保存失败'), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {

        });
      } else {
        Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
          if (this.comObj.props.saveCallBack) {
            this.comObj.props.saveCallBack();
          }
          this.replyStore.doClear();
          this.doSearch();
        });
      }
    });
  }

  @action
  addContact = () => {
    this.replyRef.setVisible(true, () => {
      this.replyRef.getInputFocus();
      // 设置相关商机 or 相关联系人的默认值      
      if (this.params.chanceId && this.params.chanceId > 0) {
        this.replyStore.setState({ attach: { chance: [{ id: this.params.chanceId }] } });
      }
      if (this.params.contacterId && this.params.contacterId > 0) {
        this.replyStore.setState({ attach: { contacter: [{ id: this.params.contacterId }] } });
      }
    });
  }

  @action
  showPhotos(photoIndex, photoFiles) {
    this.photoVisible = true;
    this.photoIndex = photoIndex;
    this.photoFiles = photoFiles;
  }

  @action
  hidePhotos() {
    this.photoVisible = false;
    this.photoIndex = 0;
    this.photoFiles = [];
  }

  getAttachList = () => ( // 添加操作内 attach配置
    new Promise((resolve) => {
      const currentPath = this.comObj.props.location.pathname;
      const browserPath = currentPath + "/browser";
      const uploadPath = currentPath + "/upload";
      let attachList = [];
      const contactWays = toJS(this.contactWay);
      attachList.push({
        key: 'workFlow', // 字符串
        type: 'browser',
        path: browserPath,
        config: {
          type: 16,
          isSingle: false,
          hasAdvanceSerach: true,
        },
        iconType: 'flow',
        iconBgColor: '#61A8F5',
        text: getLabel("18015", '流程'),
      });

      attachList.push({
        key: 'document',
        type: 'browser',
        path: browserPath,
        config: {
          type: 9,
          isSingle: false,
        },
        iconType: 'file',
        iconBgColor: '#61A8F5',
        text: getLabel("58", '文档'),
      });

      attachList.push({
        key: 'project',
        type: 'browser',
        path: browserPath,
        config: {
          type: 8,
          isSingle: false,
        },
        iconType: 'relevant-project',
        iconBgColor: '#61A8F5',
        text: getLabel("101", '项目'),
      });

      if (this.params.rightType) {
        let dataParams = {};
        // if(this.params.rightType === "my"){
        //   dataParams.crmManager = 4;
        // }else{
        //   dataParams = {};
        // }
        attachList.push({
          key: 'customer',
          type: 'browser',
          path: browserPath,
          config: {
            type: "7",
            isSingle: true,
            dataParams: dataParams
          },
          iconType: 'customer',
          iconBgColor: '#61A8F5',
          text: getLabel("136", '客户'),
        });
      }

      attachList.push({
        key: 'chance',
        type: 'browser',
        path: browserPath,
        config: {
          type: "sellchance",
          isSingle: true,
          dataParams: { customer: this.params.customerId }
        },
        iconType: 'asset',
        iconBgColor: '#61A8F5',
        text: getLabel("32922", '商机'),
      });

      attachList.push({
        key: 'contacter',
        type: 'browser',
        path: browserPath,
        config: {
          type: "67",
          isSingle: true,
          dataParams: { customerid: this.params.customerId }
        },
        iconType: 'customer',
        iconBgColor: '#61A8F5',
        text: getLabel("572", '联系人'),
      });

      attachList.push({
        key: 'file',
        type: 'upload',
        path: uploadPath,
        config: {
          multiSelection: true,
        },
        iconType: 'file',
        iconBgColor: '#F3B04C',
        text: getLabel("156", '附件'),
      });
      attachList.push({ // 选择器 传type为picker
        key: 'contactWay',
        type: 'picker',
        config: {
          title: getLabel(514789, "请选择联系方式"),
          cols: 1,
          data: contactWays,
          value: [],
        },
        iconType: 'approval',
        iconBgColor: '#61A8F5',
        text: getLabel(15858, "联系方式"),
      });
      resolve({
        attachList: attachList
      });
    })
  )
  @action
  setRemark = (remark, callback) => {
    this.remark = { ...this.remark, ...remark };
    callback && (this.callback = callback);
  }
  @action
  saveRemarkCmd = () => {
    Apis.saveRemarkCmd(this.remark).then(result => {
      if (result.status == "success") {
        this.comObj.replyRef && this.comObj.replyRef.setVisible(false);
        this.remarkStore.doClear();
        this.callback && this.callback.init();
      } else {
        Bubble.error(result.msgcode);
      }
    })
  }
}